<?php

namespace LaraExt\LoginLog;

use LaraExt\LoginLog\Models\LoginLog;

class LoginLogHelper
{
    public static function getClientIp()
    {
        if (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        }
        if (getenv('HTTP_X_REAL_IP')) {
            $ip = getenv('HTTP_X_REAL_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
            $ips = explode(',', $ip);
            $ip = $ips[0];
        } elseif (getenv('REMOTE_ADDR')) {
            $ip = getenv('REMOTE_ADDR');
        } else {
            $ip = '0.0.0.0';
        }

        return $ip;
    }

    public static function saveLogoutLog($user_account, $user_name)
    {
        LoginLog::insert([
            'user_account' => $user_account,
            'user_name' => $user_name,
            'action' => 'logout',
            'ip' => self::getClientIp(),
            'created_at' => date('Y-m-d H:i:s'),
        ]);
    }

    public static function saveLoginLog($user_account, $user_name)
    {
        LoginLog::insert([
            'user_account' => $user_account,
            'user_name' => $user_name,
            'action' => 'login',
            'ip' => self::getClientIp(),
            'created_at' => date('Y-m-d H:i:s'),
        ]);
    }
}
